﻿// -----------------------------------------------------------------------
// <copyright file="GenericRepository.cs" company="Microsoft">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

using System.Linq.Expressions;

namespace Coslen.Framework.Generics
{
    using System;
    using System.Data;
    using System.Data.Entity;
    using System.Linq;
    using System.Linq.Expressions;
    using LinqKit;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public abstract class GenericRepository<C, T> : IGenericRepository<T>
        where T : class
        where C : DbContext, new()
    {
        private C _entities = new C();
        private bool disposed;

        public C Context
        {
            get { return _entities; }
            set { _entities = value; }
        }

        #region IGenericRepository<T> Members

        public virtual IQueryable<T> GetAll()
        {
            IQueryable<T> query = _entities.Set<T>();
            return query;
        }

        public IQueryable<T> FindBy(Expression<Func<T, bool>> predicate)
        {
            IQueryable<T> query = _entities.Set<T>().AsExpandable().Where(predicate);
            return query;
        }

        public IQueryable<T> FindByIncluding(Expression<Func<T, bool>> predicate, params string[] includeProperties)
        {
            IQueryable<T> query = _entities.Set<T>().AsExpandable().Where(predicate);

            foreach (var includeProperty in includeProperties)
            {
                query = query.Include(includeProperty);
            }

            return query;
        }

        public virtual void Add(T entity)
        {
            _entities.Set<T>().Add(entity);
        }

        public virtual void Delete(T entity)
        {
            _entities.Set<T>().Remove(entity);
        }

        public virtual void Edit(T entity)
        {
            _entities.Entry(entity).State = EntityState.Modified;
        }

        public virtual void Save()
        {
            _entities.SaveChanges();
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion

        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    _entities.Dispose();
                }
            }

            disposed = true;
        }
    }
}